import { emailCheck, validatePhoneNumber } from "@/utils/validate";
import { ElMessage } from "element-plus";
import { isEmpty } from "element-plus/es/utils/types.mjs";
import { defineStore } from "pinia";
import { computed, reactive, ref } from "vue";

export const useUserStore = defineStore(
  'user',
  () =>  {
    //token
    const token = ref('')
    const setToken = (newToken:string) => {
      token.value = newToken
    }
    const removeToken = () => {
      token.value = ''
    }

    //首页右上角信息展示
    const userInfo = reactive({
      name:'',
      avatarUrl:''
    })



    //用户id
    const userId = ref()
    const setUserId = (newId:number) =>{
      userId.value = newId
    }
    const removeUserId = () => {
      userId.value = ''
    }

    //验证码
    const countdownDuration = 60; // 倒计时秒数
    let intervalId: number | undefined;

    const remainingTime = ref<number>(countdownDuration);
    const isCountingDown = ref<boolean>(false);

    const buttonText = computed(() =>
      isCountingDown.value ? `${remainingTime.value}s 后重新发送` : '发送验证码'
    );

    const PHONE_ERROR_MSG = {
      NONE:"手机号不能为空",
      WUXIAO:"手机号码格式无效"
    }

    const EMAIL_ERROR_MSG = {
      NONE:"邮箱不能为空",
      WUXIAO:"邮箱号格式无效"
    }

    const startCountdown = (phone:string,type:string) => {
      if (isCountingDown.value) return;
      if(type === 'phone'){
        if(isEmpty(phone)){
          ElMessage.error(PHONE_ERROR_MSG.NONE)
          return false
        }
        if(!validatePhoneNumber(phone)){
          ElMessage.error(PHONE_ERROR_MSG.WUXIAO);
          return false
        }
      }else if(type === 'email'){
        if(isEmpty(phone)){
          ElMessage.error(EMAIL_ERROR_MSG.NONE)
          return false
        }
        if(!emailCheck(phone)){
          ElMessage.error(EMAIL_ERROR_MSG.WUXIAO);
          return false
        }
      }
      ElMessage.success('验证码已发送，请注意查收');
      isCountingDown.value = true;
      remainingTime.value = countdownDuration;
      intervalId = window.setInterval(() => {
        if (remainingTime.value <= 1) {
          clearInterval(intervalId!);
          isCountingDown.value = false;
        } else {
            remainingTime.value -= 1;
          }
      }, 1000);
    };

    return {token,setToken,removeToken,buttonText,startCountdown,userId,setUserId,removeUserId,userInfo}
  },
  {
    persist:true
  }
)
